package com.guangzhi.weijianzhi.company.center;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.guangzhi.weijianzhi.R;
import com.guangzhi.weijianzhi.activity.LoginActivity;
import com.guangzhi.weijianzhi.context.WeiJianZhiEntity;
import com.guangzhi.weijianzhi.fragment.BaseFragment;
import com.guangzhi.weijianzhi.http.HttpRequestUtils;
import com.guangzhi.weijianzhi.http.MyAsyncHttpResponseHandler;
import com.guangzhi.weijianzhi.utils.CommonUtils;
import com.guangzhi.weijianzhi.utils.Misc;
import com.guangzhi.weijianzhi.utils.PopuUtils;
/**
 * 用户个人中心
 * @author Administrator
 *
 */
public class ComCenterFragment extends BaseFragment implements OnClickListener {
	private PopupWindow mPop;
	private ImageView mOpenImaage;
	private Uri imageUri;
	private File outputimage =null;
	private ImageView mIcon;
	private ArrayList<String> imagelist = new ArrayList<String>();// 图片路径集合
	private ArrayList<String> imagenameList = new ArrayList<String>();
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View inflate = View.inflate(getActivity(), R.layout.tz_main_center_layout, null);
		initView(inflate);
		
		if(Misc.notNull(WeiJianZhiEntity.userPic)){
			
			CommonUtils.showDfImage(WeiJianZhiEntity.userPic,mIcon);
		}
		
		return inflate;
	}
	
	private void initView(View inflate) {
		// TODO Auto-generated method stub
		initTitle(inflate);
		titleTextV.setText("个人中心");
	    mIcon = (ImageView) inflate.findViewById(R.id.icon);
	    inflate.findViewById(R.id.com_info).setOnClickListener(this);
	    
	    inflate.findViewById(R.id.setting).setOnClickListener(this);
	    
	    mIcon.setOnClickListener(this);
		goBack.setCompoundDrawables(null, null, null, null);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.icon:
			
			if( Misc.notNull(WeiJianZhiEntity.access_token)){
				showOpen();
				
			}else{
				startActivity(new Intent(getActivity(),LoginActivity.class));
			}
			
			break;

		case R.id.com_info:
			startActivity(new Intent(getActivity(),CompileCompanyInfoActivity.class));
			break;
		case R.id.setting:
		     startActivity(new Intent(getActivity(),ComSettingActivity.class));
		    break;
		case R.id.camera:
			mPop.dismiss();
			openCamera();
			break;
		
	case R.id.photo:
		takePhotosFromLocal();
		mPop.dismiss();
		break;
	case R.id.cancel:
		mPop.dismiss();
		break;
		}     
	}
	
	private void showOpen() {
		// TODO Auto-generated method stub
		View inflate = View.inflate(getActivity(), R.layout.tz_photo_camera_layout, null);
		mPop = PopuUtils.showPou(View.inflate(getActivity(), R.layout.main_activity_layout, null),inflate, this, getActivity());
		inflate.findViewById(R.id.camera).setOnClickListener(this);
		inflate.findViewById(R.id.photo).setOnClickListener(this);
		inflate.findViewById(R.id.cancel).setOnClickListener(this);
	}
	
	private void openCamera() {
		if (outputimage!=null && outputimage.exists()) {
			outputimage.delete();
		}
		outputimage  = Misc.createFile();
		imageUri = Uri.fromFile(outputimage);
		
		
		
        Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 指定调用相机拍照后照片的储存路径
        cameraintent.putExtra(MediaStore.EXTRA_OUTPUT,
        		imageUri);
		startActivityForResult(cameraintent, 8);
	}
	
	/**
	 * 从本地相册获取
	 */
	private void takePhotosFromLocal() {
		try {
			if (outputimage!=null&&outputimage.exists()) {
				outputimage.delete();
			}
			outputimage  = Misc.createFile();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(intent, 10);
	}
	
	  public void onActivityResult(int requestCode, int resultCode, Intent data) {
	        switch (requestCode) {
	        case 8:// 当选择拍照时调用
	            startPhotoZoom(imageUri);
	            break;
	        case 10:// 当选择从本地获取图片时 
	            // 做非空判断，当我们觉得不满意想重新剪裁的时候便不会报异常，下同
	            if (data != null)
	                startPhotoZoom(data.getData());
	            break;
	        case 11:// 返回的结果
	            if (data != null)
	                sentPicToNext(data);
	            break;
	        }
	        super.onActivityResult(requestCode, resultCode, data);
	    }
	  
	  
	  
	  
	  private void startPhotoZoom(Uri uri) {
	        Intent intent = new Intent("com.android.camera.action.CROP");
	        intent.setDataAndType(uri, "image/*");
	        // crop为true是设置在开启的intent中设置显示的view可以剪裁
	        intent.putExtra("crop", "true");

	        // aspectX aspectY 是宽高的比例
	        intent.putExtra("aspectX", 1);
	        intent.putExtra("aspectY", 1);

	        // outputX,outputY 是剪裁图片的宽高
	        intent.putExtra("outputX", 300);
	        intent.putExtra("outputY", 300);
	        intent.putExtra("return-data", true);
	        intent.putExtra("noFaceDetection", true);
	        startActivityForResult(intent, 11);
	    }
	  
	  
	  private void sentPicToNext(Intent picdata) {
		  
		  
	        Bundle bundle = picdata.getExtras();
	        if (bundle != null) {
	            final Bitmap photo = bundle.getParcelable("data");
	            mIcon.setImageBitmap(photo);
	            String string = outputimage.toString();///storage/sdcard0/20150628192426
	            System.out.println(string);
	            
	            
	            // 图像保存到文件中  
                FileOutputStream foutput = null;  
                try {  
                	File createFile = Misc.createFile();
                	try {
						createFile.createNewFile();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                    foutput = new FileOutputStream(createFile);  
                    photo.compress(Bitmap.CompressFormat.JPEG, 100, foutput);  
                    ///storage/sdcard0/20150703145040.jpg
                    String string2 = createFile.toString();
                    
                    final String replaceAll = string2.replaceAll(Environment.getExternalStorageDirectory().getPath()
            				+ File.separator, "");
                    
                    imagelist.add(string2);
                    imagenameList.add(replaceAll);
                    
                    CommonUtils.submitImages(getActivity(), imagelist, imagenameList);
                    
                    HttpRequestUtils.doHttpUserPic(replaceAll, new MyAsyncHttpResponseHandler(getActivity().getSupportFragmentManager(),getResources()) {
                    	
                    	
                    	@Override
                    	public void onSuccess(int arg0, Header[] arg1,
                    			byte[] arg2) {
                    		// TODO Auto-generated method stub
                    		super.onSuccess(arg0, arg1, arg2);
                    		
                    		try {
								JSONObject jsonO = new JSONObject(new String(arg2));
								if(jsonO.optBoolean("status")){
									Misc.alert("头像上传成功");
									mIcon.setImageBitmap(photo);
									WeiJianZhiEntity.userPic =replaceAll;
								}else{
									Misc.alert(jsonO.optString("errMessage"));
								}
								
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
                    	}
                    	
					});
                } catch (FileNotFoundException e) {  
                    e.printStackTrace();  
                }finally{  
                    if(null != foutput){  
                        try {  
                            foutput.close();  
                        } catch (IOException e) {  
                            e.printStackTrace();  
                        }  
                    }  
                }  
}

	  }

}

